package com.novel.controller.system;

import com.novel.common.enums.UserIdentifyEnum;
import com.novel.common.vo.NovelMailVo;
import com.novel.common.vo.SystemParamVo;
import com.novel.controller.other.BaseController;
import com.novel.common.exception.CustomerException;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.system.ManageParam;
import com.novel.pojo.system.Recharge;
import com.novel.pojo.system.User;
import com.novel.service.*;
import com.novel.utils.GsonTool;
import com.novel.utils.MailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;


@Controller
@RequestMapping("manage")
public class ManagerController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ApplyAuthorService applyAuthorService;

    @Autowired
    private NovelCommentService commentService;

    @Autowired
    private RechargeService rechargeService;

    @Autowired
    private NovelService novelService;

    @Autowired
    private MailUtils mailUtils;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private SysLogService sysLogService;


    /**
     * 校验用户是否登录并且有登录权限
     */
    public ModelAndView checkPermissionAndLogin(ModelAndView mv, String targetView) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.setViewName(targetView);
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 校验用户权限
     */
    public boolean checkPermissionAndLogin() {
        User user = getUserInformation();
        if (user == null) {
            throw new CustomerException("用户未登录");
        }
        return checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify());
    }


    /**
     * 跳转到分页查询系统日志信息页面
     */
    @GetMapping("system/log")
    public ModelAndView toSystemLog(ModelAndView mv,
                                    @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.addObject("pageInfo", sysLogService.querySysLogListByPage(pageNum, 12));
            mv.setViewName("manage/system_log");
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 跳转到分页查询系统参数页面
     */
    @GetMapping("system/param")
    public ModelAndView toSystemParam(ModelAndView mv) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            //获取系统参数内容
            mv.addObject("paramList", managerService.getManageParamVo());
            mv.setViewName("manage/system_param");
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 保存系统参数
     */
    @PostMapping("system/param/save")
    @ResponseBody
    public boolean saveSystemParam(ManageParam manageParam) {
        if (checkPermissionAndLogin()) {
            return managerService.updateManageParam(manageParam);
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 系统访问压力数据
     */
    @PostMapping("system/power")
    @ResponseBody
    public List<Map<String, Object>> getSystemPower() {
        if (checkPermissionAndLogin()) {
            return managerService.getSystemPowerMap();
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 订单金额充值数据
     */
    @PostMapping("order/map")
    @ResponseBody
    public List<Map<String, Object>> getOrderMap() {
        if (checkPermissionAndLogin()) {
            return managerService.getOrderCostMap();
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 跳转到充值管理界面
     */
    @GetMapping("recharge")
    public ModelAndView toReCharge(ModelAndView mv,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.addObject("pageInfo", rechargeService.getRechargeList(pageNum, 12));
            mv.setViewName("manage/recharge_list");
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 跳转到新增充值数额界面
     */
    @GetMapping("recharge/toAdd")
    public ModelAndView toAddRecharge(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "manage/recharge_create");
    }

    /**
     * 保存充值类目信息
     */
    @PostMapping("recharge/add")
    @ResponseBody
    public boolean addRecharge(Recharge recharge) {
        if (checkPermissionAndLogin()) {
            recharge.setId(UUID.randomUUID().toString());
            recharge.setCreatedIp(getUserIpAddress());
            recharge.setCreatedUser(getUserInformation().getUserId());
            recharge.setCreatedTime(new Date());
            return rechargeService.insertRechargeItem(recharge);
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 删除充值类目信息
     */
    @PostMapping("recharge/delete")
    @ResponseBody
    public boolean deleteRecharge(String id) {
        if (checkPermissionAndLogin()) {
            return rechargeService.deleteRechargeItemById(id);
        }
        throw new CustomerException("权限校验失败!");
    }


    /**
     * 删除评论
     */
    @PostMapping("comment/delete")
    @ResponseBody
    public boolean deleteComment(String id) {
        if (checkPermissionAndLogin()) {
            return commentService.deleteCommentInfoByCommentId(id, getUserInformation());
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 跳转到评论管理界面
     */
    @GetMapping("toComment")
    public ModelAndView toComment(ModelAndView mv,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageNum) {

        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.setViewName("manage/comment_manage");
            //查询数据，设置返回
            mv.addObject("pageInfo", commentService.queryCommentByManager(pageNum, 15));
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 跳转到管理员界面
     */
    @GetMapping(value = {"/", "index"})
    public ModelAndView ToManagerLogin(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "manage/index");
    }


    /**
     * 获取系统参数
     */
    @PostMapping("index/param")
    @ResponseBody
    public SystemParamVo getSystemParamData() {
        return managerService.getSystemParamInfo();
    }


    /**
     * 跳转到管理员登录
     */
    @GetMapping("/toLogin")
    public ModelAndView toLogin(ModelAndView mv) {
        mv.setViewName("manage/login");
        return mv;
    }


    /**
     * 删除书籍
     */
    @PostMapping("novel/delete")
    @ResponseBody
    public boolean deleteNovel(String novelId) {
        if (checkPermissionAndLogin() && StringUtils.isNotBlank(novelId)) {

            Novel novel = novelService.getNovelInfoByNovelId(novelId);

            boolean result = novelService.deleteNovel(novelId);

            if (result) {
                //删除成功，发送邮件提醒作者
                User userInfo = userService.getUserInfo(novel.getAuthorId());

                mailUtils.sendEmail(userInfo.getUserEmail(),
                        "亲爱的作者你好，你的书籍被管理员删除",
                        "书籍信息:" + GsonTool.toJson(NovelMailVo.convert(novel)));
            }
            return result;
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 跳转到书籍管理界面
     */
    @GetMapping("/toNovel")
    public ModelAndView toNovelManage(ModelAndView mv,
                                      @RequestParam(required = false, defaultValue = "1") Integer pageNum) {

        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.setViewName("manage/novel_manage");
            //查询数据，设置返回
            mv.addObject("pageInfo", novelService.findAllNovelByPage(pageNum, 12, ""));
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 跳转到用户管理界面
     */
    @GetMapping("/toUser")
    public ModelAndView toUserManage(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "manage/user_manage");
    }

    /**
     * 跳转到通过作家申请界面
     */
    @GetMapping("/toPassApply")
    public ModelAndView toPassApply(ModelAndView mv,
                                    @RequestParam(required = false, defaultValue = "1") Integer pageNum) {

        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/manage/toLogin");
        } else if (checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
            mv.setViewName("manage/pass_author_apply");
            //查询数据，设置返回
            mv.addObject("pageInfo", applyAuthorService.queryApplyAuthorInfoByPage(pageNum, 10));
        } else {
            mv.setViewName("redirect:/index");
        }
        return mv;
    }

    /**
     * 作家管理
     */
    @GetMapping("/toAuthor")
    public ModelAndView toAuthor(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "manage_author_manage");
    }

    /**
     * 管理员信息界面
     */
    @GetMapping("/toInfo")
    public ModelAndView toInfo(ModelAndView mv) {
        checkPermissionAndLogin(mv, "manage/manage_info");
        //重新设置查询用户信息
        setUserInformation(userService.getUserInfo(getUserInformation().getUserId()));
        return mv;
    }

    /**
     * 跳转到管理员密码修改界面
     */
    @GetMapping("/toChangePwd")
    public ModelAndView toChangePwd(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "manage/manage_change_pwd");
    }

    /**
     * 管理员密码修改
     */
    @PostMapping("change/password")
    @ResponseBody
    public boolean changeManagerPassword(String oldPassword, String newPassword) {
        User user = getUserInformation();
        if (user == null) {
            throw new CustomerException("用户未登录!");
        }

        if (StringUtils.isNotBlank(oldPassword) &&
                StringUtils.isNotBlank(newPassword) &&
                !StringUtils.equals(oldPassword, newPassword)) {
            user.setPassword(newPassword);
            boolean result = userService.ChangePassword(user);
            if (result) {
                setUserInformation(user);
            }
            return result;
        }
        throw new CustomerException("新旧密码相同!");
    }

    /**
     * 通过作家申请记录
     */
    @PostMapping("pass/apply")
    @ResponseBody
    public boolean passApply(String id) {
        if (checkPermissionAndLogin()) {
            return applyAuthorService.passApplyAuthor(id, getUserInformation().getUserId(), getUserIpAddress());
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 拒绝作家申请记录
     */
    @PostMapping("reject/apply")
    @ResponseBody
    public boolean rejectApply(String id) {
        if (checkPermissionAndLogin()) {
            return applyAuthorService.rejectUserApplyAuthor(id, getUserInformation().getUserId(), getUserIpAddress());
        }
        throw new CustomerException("权限校验失败!");
    }


    /**
     * 管理员退出登录
     */
    @GetMapping("/logout")
    public ModelAndView logout(ModelAndView mv) {
        clearUserInformation();
        mv.setViewName("redirect:/index");
        return mv;
    }


    @PostMapping("change/info")
    @ResponseBody
    public boolean changeManagerInfo(User send) {
        User user = getUserInformation();
        if (user == null) {
            throw new CustomerException("请登录后操作");
        }
        send.setUserId(user.getUserId());
        return userService.ChangePersonal(send);
    }

    /**
     * 管理员登录验证
     */
    @PostMapping("login")
    @ResponseBody
    public boolean managerLogin(String username, String password, String varCode) {
        if (compareVerCode(varCode)) {
            User user = userService.Login(username, password);
            if (!checkUserPermission(UserIdentifyEnum.MANAGER, user.getIdentify())) {
                throw new CustomerException("你没有登录管理员端的权限!");
            }
            setUserInformation(user);
            return true;
        }
        throw new CustomerException("验证码输入错误!");
    }


}
